package cb_rec

import org.apache.spark.ml.linalg
import org.apache.spark.ml.linalg.{SparseVector, Vectors}

/**
  * Created by hunter.coder 涛哥  
  * 2019/5/4 9:06
  * 交流qq:657270652
  * Version: 1.0
  * 更多学习资料：https://blog.csdn.net/coderblack/
  * Description:
  **/
object DistUtil {

  def cosineDist( v1:SparseVector,v2:SparseVector)={

    val dv1 = v1.toDense.values
    val dv2 = v2.toDense.values

    val sum1 = Math.sqrt(v1.values.map(Math.pow(_,2)).sum)
    val sum2 = Math.sqrt(v2.values.map(Math.pow(_,2)).sum)

    val multi = dv1.zip(dv2).map(tp=>tp._1*tp._2).sum

    multi/(sum1*sum2)

  }


  def main(args: Array[String]): Unit = {
    val v1= Vectors.sparse(4,Array[Int](0,1,3),Array[Double](1,1,2))
    val v2 = Vectors.sparse(4,Array[Int](1,2,3),Array[Double](2,2,1))
    println(cosineDist(v1.toSparse, v2.toSparse))
  }

}
